import json
import sys
import os
from PySide6.QtGui import QImage, QPixmap
from PySide6.QtWidgets import (
    QApplication, QMainWindow, QWidget, QVBoxLayout, QPushButton, QLabel,QHBoxLayout,QMessageBox
)
from output_1 import Ui_MainWindow
from PySide6.QtCore import Qt
from PySide6.QtCore import QThread, Signal, QObject
from page_paging import RequestResponse
import requests

# 下载线程工作类对象
class Down_Worker(QObject):
    finished = Signal(str)  # 任务完成信号

    def __init__(self,url):
        super(Down_Worker, self).__init__()
        self._is_running = True  # 控制线程运行的标志
        self.url = url
    # 获取系统文件夹
    def get_default_download_folder(self):
        import winreg
        sub_key = r'SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders'
        with winreg.OpenKey(winreg.HKEY_CURRENT_USER, sub_key) as key:
            download_dir = winreg.QueryValueEx(key, '{374DE290-123F-4565-9164-39C4925E467B}')[0]
        return download_dir

    # 下在函数，耗时工作
    def run(self):
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36'}

        res = requests.get(self.url, headers=headers)
        path_aaa = self.get_default_download_folder()
        # 获取程序文件名
        file_name = res.headers.get('content-disposition').split('"')[1]
        path_h = os.path.join(path_aaa, file_name)

        with open(path_h, 'wb') as f:
            f.write(res.content)

        self.finished.emit('ok')

    def stop(self):
        """安全停止线程的方法"""
        self._is_running = False

# 组件列表分页对象
class Component_list_paging:
    def __init__(self):
        # 项目路径
        self.project_path = os.path.dirname(os.path.abspath('.'))
        self.sum_page_list = self.get_data()                # 存储全部页的数据
        self.current_index = 0                              # 当前页索引
        self.now_page = self.sum_page_list[self.current_index] # 当前页数据


    def get_data(self):
        sum_page_list = []
        json_list_path = os.path.join(self.project_path,'datajson')
        # 读取数据列表
        for i in os.listdir(json_list_path):
            with open(os.path.join(json_list_path,i),'r',encoding='utf-8') as json_file:
                data = json_file.read()
                data = json.loads(data)
            sum_page_list.append(data)
        return sum_page_list

    # 获取下一页数据
    def next_page(self):
        if self.current_index >= len(self.sum_page_list) - 1:
            return
        else:
            self.current_index += 1
            self.now_page = self.sum_page_list[self.current_index]
    # 获取上一页数据
    def previous_page(self):
        if self.current_index == 0:
            return
        else:
            self.current_index -= 1
            self.now_page = self.sum_page_list[self.current_index]

# 组件列表对象
class Componet_list(QWidget):
    def __init__(self,title,url,img_path=None):
        super(Componet_list, self).__init__()
        # 设置组件容器的基本属性
        self.setFixedHeight(101)       # 固定高度
        self.setFixedWidth(851)        # 固定宽度
        # 初始化线程和工作者
        self.thread = None
        self.worker = None
        # 获取创建属性
        self.title = title  # 列表标题
        self.url = url  # 下载url
        self.img_path = img_path  # 图片路径

        self.create_component()
        self.layout_component()
        self.connect_signals()

    # 创建组件函数
    def create_component(self):
        self.but_down =  QPushButton('下载')         # 下载按钮
        self.but_down.setFixedWidth(100)
        if self.url == None:
            self.but_down.setEnabled(False)

        self.img_lable = QLabel()  # 图片容器
        self.img_lable.setFixedSize(80, 80)  # 固定图片大小
        self.img_lable.setAlignment(Qt.AlignCenter)  # 图片居中
        if self.img_path == None:
            img_path = os.path.join(os.path.dirname(os.path.abspath('.')), 'img', 'img_data.png')
            self.img_path = img_path
        self.img = QImage(self.img_path)        # 加载图片
        self.img_lable.setPixmap(QPixmap.fromImage(self.img))

        self.title_label = QLabel(self.title)   # 标题
    # 布局放置组件函数
    def layout_component(self):
        self.main_layout = QHBoxLayout(self)        # 创建水平布局
        self.main_layout.addWidget(self.img_lable)
        self.main_layout.addWidget(self.title_label)
        self.main_layout.addWidget(self.but_down)

        # 主容器布局设置
        self.setLayout(self.main_layout)

    # 下载按钮信号
    def connect_signals(self):
        self.but_down.clicked.connect(self.requests_)

    # 下载按钮槽函数
    def requests_(self):
        self.but_down.setEnabled(False)
        # 创建线程工作类对象
        self.thread = QThread()
        self.worker = Down_Worker(self.url)
        # 将工作对象移动到线程中
        self.worker.moveToThread(self.thread)
        # 连接信号和槽（线程间通信）
        self.thread.started.connect(self.worker.run)  # 线程启动时执行任务
        self.worker.finished.connect(self.handle_completion)  # 任务完成

        self.thread.start()
    # 线程完成弹出提示框
    def handle_completion(self):
        QMessageBox.information(None, "提示", "下载完成")

# 线程工作类对象
class Worker(QObject):
    # 定义信号
    progress_updated = Signal(int)      # 进度更新信号
    finished = Signal(str)              # 任务完成信号

    def __init__(self,sreach_text):
        super().__init__()
        self._is_running = True  # 控制线程运行的标志
        self.sreach_text = sreach_text

    # 耗时操作，搜索数据
    def long_runing_task(self):
        self.progress_updated.emit(50)
        RequestResponse(self.sreach_text)

        # 任务完成时发送完成信号
        self.finished.emit("ok")

    def stop(self):
        """安全停止线程的方法"""
        self._is_running = False


# 主窗口对象
class MainWindow(QMainWindow, Ui_MainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.setupUi(self)
        # 初始化线程和工作者
        self.thread = None
        self.worker = None
        self.progressBar.hide()                       # 进度条隐藏
        self.lineEdit.setPlaceholderText("请输入需要下载的游戏MOD英文名")

        self.connect_signals()                        # 绑定信号
        self.scroll_region_initialization()           # 滚动区域初始化

    # 滚动区域初始化配置函数
    def scroll_region_initialization(self):
        internal_container = QWidget()                     # 创建滚动区域内部容器
        self.layout_ic = QVBoxLayout(internal_container)   # 为内部容器创建垂直布局
        self.layout_ic.addStretch()                        # 布局内容靠上显示（弹性布局）
        self.scrollArea.setWidget(internal_container)      # 将内部容器添加到滚动区域内
        self.scrollArea.setWidgetResizable(True)           # 允许调整大小

    # 绑定信号
    def connect_signals(self):
        self.pushButton_6.clicked.connect(self.but_6) # 搜索按钮
        self.pushButton_8.clicked.connect(self.but_8) # 下一页
        self.pushButton_7.clicked.connect(self.but_7) # 上一页

    # 数据显示
    def display_(self,data_1):
        # 删除上一页数据
        self.layout_ic.deleteLater()
        self.scroll_region_initialization()
        # 数据渲染
        for i in self.clp.now_page:
            # 添加组件
            self.layout_ic.addWidget(
                Componet_list(
                    title=i['title'],
                    url=i['down_src'],
                    img_path=None
                )
            )

    # 搜索按钮槽函数
    def but_6(self):
        search_text = self.lineEdit.text()
        self.progressBar.show()                                    # 进读条显示
        self.progressBar.setValue(0)
        self.pushButton_6.setEnabled(False)
        # 创建线程工作类对象
        self.thread = QThread()
        self.worker = Worker(search_text)
        # 将工作对象移动到线程中
        self.worker.moveToThread(self.thread)
        # 连接信号和槽（线程间通信）
        self.thread.started.connect(self.worker.long_runing_task)    # 线程启动时执行任务
        self.worker.progress_updated.connect(self.progress_updated)  # 进度更新
        self.worker.finished.connect(self.handle_completion)         # 任务完成

        # 线程结束后清理资源
        self.worker.finished.connect(self.thread.quit)
        self.worker.finished.connect(self.worker.deleteLater)
        self.thread.finished.connect(self.thread.deleteLater)

        # 启动线程
        self.thread.start()

    # 进度条更新函数
    def progress_updated(self,val):
        self.progressBar.setValue(val)
    # 线程完成函数
    def handle_completion(self):
        self.progressBar.setValue(100)
        self.pushButton_6.setEnabled(True)
        # 数据显示
        self.clp = Component_list_paging()
        self.display_(self.clp.now_page)
    # 下一页槽函数
    def but_8(self):
        self.clp.next_page()
        self.display_(self.clp.now_page)
    # 上一页槽函数
    def but_7(self):
        self.clp.previous_page()
        self.display_(self.clp.now_page)



if __name__ == '__main__':
    # app = QApplication(sys.argv)
    # window = Componet_list(title='测试数据',url='http://www.cn')
    # window.show()
    # sys.exit(app.exec())

    # 主窗口
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec())
